package com.jinxin.platform.cdacsfacetalk.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdacsfacetalk.common.Constant;
import com.jinxin.platform.cdacsfacetalk.utils.FaceTalkRedisUtil;
import com.jinxin.platform.cdacsfacetalk.utils.HttpClientPoolUtil;
import com.jinxin.platform.cdacsfacetalk.utils.HttpClientResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-06-01
 * @Author: Lingnan
 **/
@EnableScheduling
@Configuration
@Slf4j
public class CdfacetalkTask {
    @Resource
    private FaceTalkRedisUtil redisUtil;
    @Value("${cdacsfacetalk.wxopen.appid}")
    private String wxopenAppid; //公众号appid
    @Value("${cdacsfacetalk.wxopen.secret}")
    private String wxopenSecret; //公众号secret
    @Value("${cdacsfacetalk.url.get-accesstoken}")
    private String getAccesstokenUrl;

    // 每隔15分钟定时刷新token
    @Scheduled(cron = "0 0/15 * * * ?  ")
    public void refreshToken(){
        Map<String, String> params = new HashMap<>();
        params.put("grant_type","client_credential");
        params.put("appid",wxopenAppid);
        params.put("secret",wxopenSecret);
        try {
            HttpClientResult result = HttpClientPoolUtil.doGet(getAccesstokenUrl, params, true);
            String content = result.getContent();
            log.info("定时刷新token，请求返回：" + content);
            if(Constant.REQUEST_STATUS_SUCCEED.equals(result.getCode())){
                JSONObject tokenJson = JSON.parseObject(content);
                if(tokenJson != null){
                    String accessToken = tokenJson.getString("access_token");
                    long expiresTime = tokenJson.getLong("expires_in");
                    String key = Constant.REDIS_WEIXIN_TOKEN_KEY;
                    redisUtil.setForTimeCustom(key,accessToken,(expiresTime-30),TimeUnit.SECONDS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
